<template>
  <div>
    <div>
      <el-form :model="filterData" label-width="0" size="mini">
        <el-row :gutter="20">
          <el-col style="width: 280px;" class="labelitem">
            <div style="width: 80px;">日期区间:</div>
            <el-date-picker type="daterange" v-model="filterData.daterange" clearable start-placeholder="起始日期"
              end-placeholder="结束日期" value-format="yyyy-MM-dd" range-separator="至" style="width: 100%;">
            </el-date-picker>
          </el-col>

          <el-col style="width: 280px;" class="labelitem">
            <div style="width: 80px;">发票号码:</div>
            <el-input placeholder="发票号码或数量发票号" v-model="filterData.num" clearable></el-input>
          </el-col>

          <el-col style="width: 280px;" class="labelitem">
            <div style="width: 80px;">开票名称:</div>
            <el-input placeholder="税收分类或货物服务名称" v-model="filterData.good" clearable></el-input>
          </el-col>

          <el-col style="width: 280px;" class="labelitem">
            <div style="width: 80px;">规格型号:</div>
            <el-input placeholder="规格型号" v-model="filterData.model" clearable></el-input>
          </el-col>



          <el-col style="width: 280px;" class="labelitem">
            <div style="width: 80px;">发票类型:</div>
            <el-select v-model="filterData.type" placeholder="发票类型" style="width: 100%;" clearable>
              <el-option label="增值税普票" value="增值税普票"></el-option>
              <el-option label="增值税专用发票" value="增值税专用发票"></el-option>
            </el-select>
          </el-col>

          <el-col style="width: 280px;" class="labelitem">
            <div style="width: 80px;">采购单号:</div>
            <el-input placeholder="关联采购单号" v-model="filterData.bind_buyreqcode" clearable></el-input>
          </el-col>

          <el-col style="width: 280px;" class="labelitem">
            <div style="width: 80px;">销项票号:</div>
            <el-input placeholder="关联销项发票号码" v-model="filterData.bind_saleticketnum" clearable></el-input>
          </el-col>

          <el-col style="width: 280px;" class="labelitem">
            <div style="width: 80px;">采购核销:</div>
            <el-select v-model="filterData.buydetail_bindstatus" placeholder="采购核销" style="width: 100%;" clearable>
              <el-option label="未核销" value="0"></el-option>
              <el-option label="已核销" value="1"></el-option>
            </el-select>
          </el-col>

          <el-col style="width: 280px;" class="labelitem">
            <div style="width: 80px;">销售状态:</div>
            <el-select v-model="filterData.saleticket_bindstatus" placeholder="销售状态" style="width: 100%;" clearable>
              <el-option label="未核销" value="0"></el-option>
              <el-option label="已核销" value="1"></el-option>
            </el-select>
          </el-col>

          <el-col style="width: 280px;" class="labelitem">
            <div style="width: 80px;">销售企业:</div>
            <el-select v-model="filterData.seller" placeholder="开票方企业名称" style="width: 100%;" filterable allow-create
              clearable>
              <el-option v-for="(item,index) in sellerlist" :key="index" :label="item.title" :value="item.title">
              </el-option>
            </el-select>
          </el-col>
          <el-col style="width: 280px;" class="labelitem">
            <div style="width: 80px;">发票用途</div>
            <el-select v-model="filterData.usage" placeholder="发票用途" style="width: 100%;" clearable allow-create
              filterable>
              <el-option label="物资发票" value="物资发票"></el-option>
              <el-option label="费用发票" value="费用发票"></el-option>
            </el-select>
          </el-col>


          <el-col style="width: 280px;" class="labelitem">
            <div style="width: 80px;">所属账套:</div>
            <el-select v-model="filterData.buyer" filterable placeholder="账套" style="width: 100%;" clearable>
              <el-option :label="item.name" :value="item.name" v-for="(item,index) in accounts"
                :key="index"></el-option>
            </el-select>
          </el-col>


          <el-col style="width: 100px;">
            <el-form-item label="" label-width="0">
              <el-button type="primary" icon='el-icon-search' @click="handleSearch">搜索发票</el-button>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
    </div>
    <div>
      <div style="text-align: right; margin-bottom: 2px;" >
          <el-button type="primary" size="mini" icon="el-icon-download" @click="handleExport">
            {{selection.length>0? '导出选中项':"导出全部"}}
          </el-button>

      </div>
      <div>
        <el-table :data="tableData" ref="tickettable" border style="width: 100%;" height="350px" highlight-current-row
          highlight-current-row @row-click="handleTicketRowClick" empty-text="暂无发票或未查询到相关发票信息"
          :header-cell-style="{'background-color': '#f5f7f9','color':'#666',border:'1px solid #ebebeb','padding':'0px'}" @selection-change="handleSelection">
          <el-table-column type="selection" align="center"></el-table-column>
          <el-table-column label="序号" type="index" align="center" fixed="left"></el-table-column>
          <el-table-column label="开票日期" prop="date" width="140px" align="center"></el-table-column>
          <el-table-column label="发票号码" prop="num" width="120px" align="left" show-overflow-tooltip>
            <template slot="header">
              <div style="text-align: center;">发票号码</div>
            </template>
          </el-table-column>
          <el-table-column label="发票代码" prop="code" width="120px" v-if="false" align="left" show-overflow-tooltip>
            <template slot="header">
              <div style="text-align: center;">发票代码</div>
            </template>
          </el-table-column>

          <el-table-column label="项目名称" prop="taxcode" width="180px" show-overflow-tooltip>
            <template v-slot="scope">
              *{{scope.row.taxname}}*{{scope.row.title}}
            </template>
          </el-table-column>
          <el-table-column label="规格" prop="model" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column label="单位" prop="unit" width="60px" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column label="数量" prop="count" width="100px" align="center"></el-table-column>
          <el-table-column label="金额" prop="total" width="100px" align="center"></el-table-column>
          <el-table-column label="税额" prop="tax" width="100px" align="center"></el-table-column>
          <el-table-column label="价税总额" prop="sum" width="110px" align="center"></el-table-column>
          <el-table-column label="发票类型" prop="type" width="140px" align="center">
            <template v-slot="scope">
              {{scope.row.type}}({{scope.row.rate*100}}%)
            </template>
          </el-table-column>
          <el-table-column label="开票方" prop="seller" width="120px" align="center"
            show-overflow-tooltip></el-table-column>

          <el-table-column label="采购核销" align="center">
            <el-table-column label="核销状态" prop="buybind_status" width="80px" align="center">
              <template v-slot="scope">
                <span v-if="scope.row.buydetail_bindstatus==0" style="color:#ff5500;">未核销</span>
                <span v-if="scope.row.buydetail_bindstatus==1" style="color:#00bc00;">已核销</span>
              </template>
            </el-table-column>
            <el-table-column label="采购单号" prop="buydetail_bindcode" width="100px" show-overflow-tooltip
              align="center"></el-table-column>
            <el-table-column label="剩余额" align="center" width="100px">
              <template v-slot="scope">
                {{(parseFloat(scope.row.sum)-parseFloat(scope.row.buydetail_bindrmb)).toFixed(2)}}
              </template>
            </el-table-column>

          </el-table-column>
          <el-table-column label="销售核销" align="center">
            <el-table-column label="销售状态" align="center" width="80px">
              <template v-slot="scope">
                <span v-if="scope.row.saleticket_bindstatus==1" style="color:#67C23A;">已售</span>
                <span v-if="scope.row.saleticket_bindstatus==0" style="color:#F56C6C;">未售</span>
                <span v-if="scope.row.saleticket_bindstatus==2" style="color:#E6A23C">部分 <i class="el-icon-info"
                    :title="'已售数量：'+scope.row.saleticket_bindcount"></i></span>
              </template>
            </el-table-column>
            <el-table-column label="关联销项" prop="saleticket_bindnums" show-overflow-tooltip width="120px"
              align="center"></el-table-column>
          </el-table-column>
          <el-table-column label="所属账套" prop="buyer" width="150px" align="center" fixed="right"
            show-overflow-tooltip></el-table-column>
          <el-table-column label="操作" fixed="right" align="center" width="80px" v-if="false">
            <template v-slot="scope">
              <el-button type="primary" size="mini" title="强制采购核销" icon="el-icon-s-check" circle
                @click="handleShowForceBuyUI(scope.$index,scope.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="display: flex;">
        <div style="flex:1;line-height: 25px; display: flex;">
          <div style="width: 160px;">总额(本页):{{parseFloat(pagesum).toFixed(3)}}</div>
          <div style="width: 160px;">金额(本页):{{parseFloat(pagetotal).toFixed(3)}}</div>
          <div style="width: 160px;">税额(本页):{{parseFloat(pagetax).toFixed(3)}}</div>


          <div style="width: 160px;">总额(选中):{{parseFloat(sumall_selection).toFixed(3)}}</div>
          <div style="width: 160px;">金额(选中):{{parseFloat(sumtotal_selection).toFixed(3)}}</div>
          <div style="width: 160px;">税额(选中):{{parseFloat(sumtax_selection).toFixed(3)}}</div>
        </div>

        <el-pagination layout=" prev, pager,next,sizes,total" :total="numrows" :page-size="pagesize"
          :current-page="curpage" prev-text="上一页" next-text="下一页" :page-sizes="[15, 30, 50,150]"
          @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
      </div>
    </div>

    <div style=" height: 350px;">
      <el-row :gutter="20">
        <el-col :span="12">
          <div style="">
            <div class="title">关联采购明细</div>
            <div style="height: 260px; overflow: hidden;overflow-y: auto;">
              <el-table :data="buydetaillist" border height="100%">
                <el-table-column label="序号" type="index"></el-table-column>
                <el-table-column label="采购单号" prop="reqcode" width="120px"></el-table-column>
                <el-table-column label="采购商品" prop="title"></el-table-column>
                <el-table-column label="规格型号" prop="model"></el-table-column>
                <el-table-column label="单位" prop="unit" width="60" show-overflow-tooltip
                  align="center"></el-table-column>
                <el-table-column label="数量" prop="count" align="center" width="100px"></el-table-column>
                <el-table-column label="销售单位" prop="seller" show-overflow-tooltip></el-table-column>
              </el-table>
            </div>
          </div>
        </el-col>
        <el-col :span="12">
          <div style="">
            <div class="title">已关联销售信息</div>
            <el-table border v-if="currentRow" :data="currentRow.salelist">
              <el-table-column label="序号" type="index"></el-table-column>
              <el-table-column label="开票日期" prop="buyticketdate"></el-table-column>
              <el-table-column label="发票类型" prop="type" width="150px">
                <template v-slot="scope">
                  {{scope.row.type}}(({{scope.row.rate*100}}%))
                </template>
              </el-table-column>
              <el-table-column label="开票名称">
                <template v-slot="scope">
                  *{{scope.row.taxname}}*{{scope.row.title}}
                </template>
              </el-table-column>
              <el-table-column label="规格型号" prop="model"></el-table-column>
              <el-table-column label="单位" prop="unit" align="center"></el-table-column>
              <el-table-column label="数量" prop="count" align="center"></el-table-column>
              <el-table-column label="金额" prop="total" align="center"></el-table-column>
            </el-table>
          </div>
        </el-col>
      </el-row>
    </div>

    <ForceBuyUI v-if="forceBuyVisible" ref="forcebuyUI" @updated="handleForceBuyUpdated"></ForceBuyUI>
  </div>
</template>

<script>
  import ForceBuyUI from './ForceBuyUI.vue';
  export default {
    components: {
      ForceBuyUI
    },
    data() {
      return {
        selection:[],
        filterData: {
          daterange: [],
          type: '',
          seller: '',
          buyer: '',
          num: '',
          model: '',
          sum: '',
          good: '',
          usage: '',
          sale_ticketstatus: '',
          buy_bindstatus: '',
          bind_buyreqcode:'',
          bind_saleticketnum:''
        },
        pagesum: 0,
        pagetotal: 0,
        pagetax: 0,
        buydetaillist: [],
        accounts: [],
        sellerlist: [],
        buyerlist: [],
        list: [],
        currentRow: null,
        forceBuyVisible: false,
        suppliers: [],
        curpage: 1,
        pagesize: 15,
        numrows: 1,
        tableData: [],
        sumtotal_selection:0,
        sumtax_selection:0,
        sumall_selection:0,
      }
    },
    mounted() {
     var now= new Date();
     var firstDay=this.formatDate(new Date(now.getFullYear(),now.getMonth(),1));
     var lastDay=this.formatDate(new Date(now.getFullYear(),now.getMonth()+1,0));
     this.filterData.daterange = [firstDay,lastDay];

      this.loadSellerList();
      this.loadDataList();
      this.loadAccount();
    },
    methods: {
      formatDate(date) {
        const yyyy = date.getFullYear();
        const mm = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的
        const dd = String(date.getDate()).padStart(2, '0');
        return `${yyyy}-${mm}-${dd}`;
      },
      handleSelection(list) {
        this.selection = list;
       this.sumtotal_selection=0;
       this.sumtax_selection=0;
       this.sumall_selection=0;

        this.selection.forEach(item=>{
            this.sumtotal_selection+=parseFloat(item.total)
            this.sumtax_selection+=parseFloat(item.tax)
            this.sumall_selection+=parseFloat(item.sum)
        })


      },
      handleExport(){
        var list=this.tableData;
        if(this.selection.length > 0){
            list=this.selection;
        }

          //导出选中
          var index = 1;
          let slist = list.map((item) => {
            let obj = {
              "序号": index,
              "开票日期": item.date,
              "发票号码": item.fphm,
              "发票代码":item.code,
              "销方单位": item.seller,
              "发票类型": item.type,
              "税收类目":item.taxname,
              "货物或服务名称":item.title,
              "规格型号":item.model,
              "单位":item.unit,
              "数量":item.count,
              "单价":item.price,
              "金额": item.total,
              "税额": item.tax,
              "价税总额": item.sum,
              "采购核销状态": item.buy_bindstatus == 1 ? "已核销" : "未核销",
              "关联采购单号": item.buy_bindcode,
              "销售状态": item.sale_bindstatus == 1 ? "已售" : "未售",
              "关联销项票号": item.saleticket_bindnum1,
              "发票备注": item.memo,
              "购方单位": item.buyer,
            }
            index++;
            return obj;
          });
          let ws = XLSX.utils.json_to_sheet(slist, {
            skipHeader: false
          });
          ws["!cols"] = [{
            wpx: 80
          }];
          let wb = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(wb, ws, '进项发票明细');
          XLSX.writeFile(wb, "进项发票明细.xlsx");

      },
      loadAccount() {
        this.axios.post("api/admin/account/list").then(res => {
          if (res.status == 200 && res.data.code == 0) {
            this.accounts = res.data.list;
          }
        })
      },
      handleTicketRowClick(row, column, event) {
        this.currentRow = row;
        this.list = this.currentRow.attach;
        if (this.tableData.length > 0) {
          this.cur = 0;
          this.curdata = this.tableData[this.cur];
        } else {
          this.cur = -1;
          this.curdata = {
            type: '-1',
            url: '',
            attach: []
          };
        }
        const params = {
          buyticketdid: row.id
        }
        this.axios.post("api/admin/buyticketdetail/getbuydetail_buyticketdid", params).then(res => {
          if (res.status == 200 && res.data.code == 1) {
            this.buydetaillist = res.data.list;
          }
        })


        return;
        this.currentRow = row;
        this.list = this.currentRow.attach;
        if (this.tableData.length > 0) {
          this.cur = 0;
          this.curdata = this.tableData[this.cur];
        } else {
          this.cur = -1;
          this.curdata = {
            type: '-1',
            url: '',
            attach: []
          };
        }
      },
      handleShowForceBuyUI(index, data) {
        this.forceBuyVisible = true;
        this.$nextTick(() => {
          this.$refs.forcebuyUI.dialogVisible = true;
          this.$refs.forcebuyUI.initData(index, JSON.parse(JSON.stringify(data)));
        })
      },
      handleSearch() {
        this.curpage = 1;
        this.loadDataList();
      },
      loadSellerList() {
        this.axios.post("api/admin/buysupplier/list_item").then(res => {
          if (res.status == 200 && res.data.code == 0) {
            this.sellerlist = res.data.list;
          }
        })
      },
      handleSizeChange: function(val) {
        this.pagesize = val;
        this.curpage = 1;
        this.loadDataList();
      },
      handleCurrentChange: function(val) {
        this.curpage = parseInt(val);
        this.loadDataList();
      },
      loadDataList() {
        var params = {
          supname: this.filterData.supname,
          num: this.filterData.num,
          sum: this.filterData.sum,
          good: this.filterData.good,
          seller: this.filterData.seller,
          model: this.filterData.model,
          curpage: this.curpage,
          type: this.filterData.type,
          pagesize: this.pagesize,
          daterange: this.filterData.daterange,
          code: this.filterData.code,
          buyer: this.filterData.buyer,
          buy_bindstatus: this.filterData.buy_bindstatus,
          saleticket_bindstatus: this.filterData.saleticket_bindstatus,
          usage:this.filterData.usage,
          bind_buyreqcode:this.filterData.bind_buyreqcode,
          bind_saleticketnum:this.filterData.bind_saleticketnum
        }
        this.axios.post("api/admin/buyticketdetail/list_by_page", params).then((res) => {
          if (res.status == 200 && res.data.code) {
            this.tableData = res.data.list;
            this.numrows = res.data.numrows;
            this.pagesum = res.data.sum;
            this.pagetotal = res.data.total;
            this.pagetax = res.data.tax;
          }
        });
      },
      handleViewAttach() {
        this.attachVisible = true;
        this.$nextTick(() => {
          this.$refs.attachUI.dialogVisible = true;
          this.$refs.attachUI.init(JSON.parse(JSON.stringify(this.currentRow.attach)));
        })
      },
      handleEdit(index, data) {
        console.log(index, data);
        this.editVisible = true;
        this.$nextTick(() => {
          this.$refs.editUI.dialogVisible = true;
          this.$refs.editUI.init(index, JSON.parse(JSON.stringify(data)));
        })
      },
      handleForceBuyUpdated(index, data) {
        this.tableData[index].buy_status = data.status;
        this.tableData[index].buy_statusmemo = data.memo;
      },
      handleEditCallback(index, data) {
        this.tableData[index].goods = data.goods;
        this.tableData[index].sum = data.sum;
        this.tableData[index].total = data.total;
        this.tableData[index].num = data.num;
        this.tableData[index].type = data.type;
        this.tableData[index].date = data.date;
        this.tableData[index].supname = data.supname;
        this.tableData[index].code = data.code;
        this.tableData[index].tax = data.tax;
        this.tableData[index].memo = data.memo;
        this.tableData[index].attach = data.attach;
        this.list = this.tableData[index].attach;
        if (this.list.length > 0) {
          this.cur = 0;
          this.curdata = this.list[this.cur];
        } else {
          this.cur = -1;
          this.curdata = {
            type: '-1',
            url: '',
            attach: []
          };
        }

      },
      handleCreate() {
        this.createVisible = true;
        this.$nextTick(() => {
          this.$refs.createUI.dialogVisible = true;
          this.$refs.createUI.initData();
        })
      },
      handleSelect(index) {
        this.cur = index;
        this.curdata = {};
        this.curdata = this.list[this.cur];

        //获取此进项绑定采购记录


      }
    }
  }
</script>

<style scoped>
  .title {
    position: relative;
    padding-left: 10px;
    margin-bottom: 15px;
    font-size: 14px;
    color: #333;
    font-weight: 700;
  }

  .title:before {
    content: "";
    position: absolute;
    top: 4px;
    left: 0;
    width: 5px;
    height: 65%;
    background-color: #249af3;
  }


  .labelitem {
    display: flex;
    line-height: 30px;
  }
</style>
